<?php

namespace app\common\service;

use app\common\service\Oss\Object;
use app\common\service\Oss\Bucket;
use think\Config;

class OssService extends BaseService {

    private $_object;
    private $_cname;
    private $_bucket;

    public function __construct($bucketName = '') {
        parent::__construct();
        $this->_bucket = new Bucket();
        $this->_object = new Object();
        if ('' == $bucketName) {
            $bucketName = Config::get("ALIYUN_OSS_BUCKET");
        }
        $this->_bucket->setBucketName($bucketName);
        $this->_object->setBucketName($bucketName);
        //$this->_cname = Config::get("OSS_DOMAIN");
    }

    /**
     * 文件上传到阿里云
     * @param type $filePath    保存在阿里云的路径和名称
     * @param type $content     文件流
     * @return boolean
     */
    public function fileUpload($filePath, $content) {
        try {
            $ossRes = $this->_object->putObject($filePath, $content);
            if ($ossRes) {
                return $filePath;
            } else {
                return FALSE;
            }
        } catch (\Exception $ex) {
            throw_exception($ex->getMessage());
        }
    }

    /**
     * 删除阿里云上的文件
     * @param type $filePath    保存在阿里云的路径和名称
     * @return type
     */
    public function fileDelete($filePath) {
        $result = $this->_object->deleteObject($filePath);
        return $result;
    }

    /**
     * 下载接口
     * @param type $filePath
     * @return type
     */
    public function downFile($filePath) {
        $result = $this->_object->getObject($filePath);
        return $result;
    }

    /**
     * 图片在阿里云上存在
     * @param type $imagePath
     * @return type
     */
    public function fileExist($filePath) {
        $result = $this->_object->doesObjectExist($filePath);
        return $result;
    }

    public function imageInfo($imagePath, $ossDomain) {
        //$imageInfo = file_get_contents($this->_cname.$imagePath."@info");
        $imageInfo = file_get_contents($ossDomain . $imagePath . "@info");
        return json_decode($imageInfo);
    }

    public function bucketList() {
        $bucketList = $this->_bucket->listBuckets();
        return $bucketList;
    }

    /**
     * 把文件保存到本地，复制到阿里云上面
     * @param	string	$url		源文件地址，只支持http开头的
     * @return path     阿里云的文件存放地址
     */
    function remoteSaveFileToOss($url) {
        //$url 为空则返回 false;
        if ($url == "")
            return $this->_addError('URL IS NULL');
        if (substr($url, 0, 7) != 'http://') {
            return $this->_addError('url 必须http://开头');
        }

        //获得文件信息
        $pathInfo = $this->_checkFileInfo($url);
        if (!$pathInfo) {
            return false;
        }
        //判断是否允许保存
        $pathInfo['extension'] = strtolower($pathInfo['extension']); //后缀全部变成小写
        $ossType = false;
        if (in_array($pathInfo['extension'], array('jpg', 'jpeg', 'gif', 'png'))) {
            $ossType = 'image';
        } elseif (in_array($pathInfo['extension'], array('mp4', 'avi', '3gp'))) {
            $ossType = 'video';
        } elseif (in_array($pathInfo['extension'], array('mp3'))) {
            $ossType = 'audio';
        }
        if (!$ossType)
            return $this->_addError($pathInfo['extension'] . ' 类型文件不支持上传到阿里云,url=' . $url);

        //--------准备上传到阿里云----------
        $newFileName = md5($url) . '.' . $pathInfo['extension']; //设置文件名，加上URL的MD5防止重复
        //文件读取到内存
        //向阿里推送图片
        $realContent = file_get_contents($url);
        $fileSavePath = $ossType . DIRECTORY_SEPARATOR . date("Ym") . DIRECTORY_SEPARATOR . $newFileName;
        $OssService = new \Common\Service\OssService();
        $picPath = $OssService->fileUpload($fileSavePath, $realContent);
        if ($picPath) {
            return $picPath;
        } else {
            return $this->_addError('文件上传到阿里云失败');
        }
    }

    /**
     * 判断文件类型
     * 
     * @param   $url    文件地址，支持网络地址
     * @return array 返回文件信息
     * array(
     *      'type' =>  文件类型
     *      'extension' =>  文件后缀
     * );
     */
    protected function _checkFileInfo($url) {
        //判断文件是否存在
        $AgetHeaders = @get_headers($url);
        if (!preg_match("|200|", $AgetHeaders[0])) {
            return $this->_addError('此文件无法获取:' . $url);
        }
        //分析
        $type = false; //文件类型
        $extension = false; //获得文件后缀
        foreach ($AgetHeaders as $v) {
            if (stristr($v, 'Content-Type')) {
                $arr = explode('/', $v);
                if (!empty($arr[1]))
                    $extension = $arr[1];
                if (!empty($arr[0])) {
                    $type = trim(str_replace('Content-Type', '', $arr[0]));
                }
            }
        }
        return array(
            'type' => $type,
            'extension' => $extension,
        );
    }

    /**
     * 获取代签名的URI
     * @param type $params
     * @return type
     */
    public function getSignUrl($params) {
        $Oss = $this->_object->getOssClient();
        $timeout = 3600;
        $options = null;
        if (!empty($params['h'] && !empty($params['w']))) {
            $options = [
                $Oss::OSS_PROCESS => 'image/resize,m_lfit,h_' . $params['h'] . ',w_' . $params['w']   // 图片缩放
            ];
        }
        $url = $Oss->signUrl($params['bucket'], $params['object'], $timeout, 'GET', $options);
        return $url;
    }

}
